/**
 * Created by way on 16/9/19.
 * 调用后台api接口
 * 所有调用需要 token 身份, 如没有则自动获取, 并保存到 sessionStorage
 */

import * as ajax from '../lib/kajax';
import cfg from '../config';
import { urlParam } from '../lib/kutil';
import { strfind, urlParams } from '../util/tool';

export function token(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.token, val);
  else {
    return cfg.dev.token ? cfg.dev.token : sessionStorage.getItem(cfg.app.token) || '';
  }
}

export function code(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.code, val);
  else {
    return sessionStorage.getItem(cfg.app.code) || '';
  }
}

export function lastCode(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.lastCode, val);
  else {
    return sessionStorage.getItem(cfg.app.lastCode) || '';
  }
}

export function docker(val) {
  if (val !== undefined)
    sessionStorage.setItem(cfg.app.docker, val);
  else {
    return sessionStorage.getItem(cfg.app.docker) || 'wx';
  }
}

export function host() {
  return docker() === 'rel' ? cfg.rel.host : cfg.api.host;
}

/**
 * 通过url中的code获得openid
 * @param tx 存储 token的 input
 * @param cb
 */
export function getToken(cb) {
  if (token())
    cb(null, token());
  else {
    if (!code())
      code(urlParam('code')); // search.substring(search.indexOf('=') + 1, search.length);
    // alert(`getToken code:${code()}`);
    /*
     if (AUTH_URL && (!code || code === 'undefined') && failcnt < 3) {
     failcnt++;
     location.href = AUTH_URL;
     }
     */

    if (code() && code() !== lastCode()) {
      // const url = docker() === 'rel' ? `${cfg.rel.host}${cfg.rel.token}`
      //   : `${cfg.api.host}${cfg.api.token}`;

      const url = `${cfg.ogs.host}${cfg.ogs.token}`;

      const sid = urlParam('sid') || urlParams('sid') || ''; // search.substring(search.indexOf('=') + 1, search.length);
      // alert(`getToken url:${url} code:${code()} sid:${sid}`);
      ajax.get(url, `code=${code()}&sid=${sid}`, (rs) => {
        // alert(`getToken code:${code()} rs:${rs}`);
        lastCode(code());
        if (rs) {
          const r = JSON.parse(rs);
          if (r.rc === 200) {
            token(r.token);
            cb(null, r.token);
          } else
            cb(new Error('获取身份失败,请退出重新进入或联系客服!'), '');
        }
      });
    } else {
      // alert(`code:${code()} code===lastCode: ${code() === lastCode()}`);
      cb(new Error('获取身份失败,请退出重新进入或联系客服!'), '');
    }
  }
}

/**
 *
 * @param url
 * @param param
 * @param cb
 * @param tk  是否必须 token，否则错误返回
 */
export function get(url, para, cb, tk) {
  if (token()) {
    // alert('token1')
    // alert(token())
    const param = para ? `${para}&token=${token()}` : `token=${token()}`;
    // url = url.indexOf(host()) === -1 ? `${host()}${url}` : url;
    // alert(`url:${url} para:${para} token:${token()}`);
    ajax.get(url, param, cb);
  } else {
    // alert('token2')
    // alert(token())
    // if (/rel.nuoyadalu.com/.test(url))
    //   docker('rel');
    getToken((err, tok) => {
      if (tk && err) {
        cb('');
        // alert(err.message);
      } else {
        const param = para ? `${para}&token=${tok}` : `token=${tok}`;
        // url = url.indexOf(host()) === -1 ? `${host()}${url}` : url;
        // alert(`get url:${url} para:${param}`);
        ajax.get(url, param, cb);
      }
    });
  }
}

export function getView(url, param, cb) {
  // alert(`url:${url} para:${para}`);
  ajax.get((url.indexOf('http://') === -1 && url.indexOf('https://') === -1)
    ? `${cfg.view.host}${url}` : url, param, cb);
}

export function getDoc(url, param, cb) {
  // alert(`url:${url} para:${para}`);
  ajax.get((url.indexOf('http://') === -1 && url.indexOf('https://') === -1)
    ? `${cfg.doc.host}${url}` : url, param, cb);
}

/**
 *
 * @param url
 * @param data
 * @param cb
 * @param tk  是否必须 token，否则错误返回
 */
export function post(url, data, cb, tk) {
  if (token()) {
    if ((typeof data) === 'object')
      data.token = token();
    else
      data = data ? `${data}&token=${token()}` : `token=${token()}`;

    url = url.indexOf(host()) === -1 ? `${host()}${url}` : url;
    // alert(`url:${url} para:${data} token:${token()}`);
    ajax.post(url, data, cb);
  } else {
    if (/rel.nuoyadalu.com/.test(url))
      docker('rel');

    getToken((err, tok) => {
      if (tk && err) {
        cb(err, '');
        // alert(err.message);
      } else {
        if ((typeof data) === 'object')
          data.token = tok;
        else
          data = data ? `${data}&token=${tok}` : `token=${tok}`;

        url = url.indexOf(host()) === -1 ? `${host()}${url}` : url;
        // alert(`post url:${url} para:${data}`);
        ajax.post(url, data, cb);
      }
    });
  }
}

export function postForm(url, data, cb) {
  if (token()) {
    data.append('token', token());
    ajax.postForm(url.indexOf(host()) === -1 ? `${host()}${url}` : url, data, cb);
  } else {
    if (/rel.nuoyadalu.com/.test(url))
      docker('rel');
    getToken((err, tk) => {
      data.append('token', tk);
      ajax.postForm(url.indexOf(host()) === -1 ? `${host()}${url}` : url, data, cb);
    });
  }
}

/**
 * 从服务器获取微信上传签名、时标
 * @param type
 * @returns {string}
 */
export function getWxSign(cb) {
  let href = `url=${location.href}`;
  href = href.replace(/&/, '%26');
  href = href.replace(/#[\s\S]*$/, '');
  ajax.get(`${cfg.api.host}${cfg.api.wxsign}`, href, rs => {
    cb(JSON.parse(rs));
  });
}
